<script setup>
	import { onLoad, onShow, onHide, onPageScroll, onReachBottom, onPullDownRefresh, onTabItemTap, onShareAppMessage } from '@dcloudio/uni-app'
	import { ref, computed, getCurrentInstance, toRef } from 'vue'
	import { useUserStore } from '@/store/user'
	import { getAddressList, getBannerList, getSpecialOffer, getVideoList } from '@/api/login'
	import { getFoodGoods } from '@/api/shop'
	import { timestampToTime } from '@/utils/common'
	
	const { ctx } = getCurrentInstance()
	const user = useUserStore()
	const config = getApp().globalData.config
	const statusHeight = ref(0)
	const menuHeight = ref(32)
	const menuWidth = ref(0)
	const contHeight = ref(66)
	const headOpacity = ref(0)
	const navImg = ref([])
	const curSwiper = ref(0)
	const waterfall = ref(null)
	const loading = ref(true)
	const loadStatus = ref('loadmore')
	const query = ref({status: 1, current: 1, size: 20})
	const total = ref(0)
	const videoList = ref([])
	const list1 = ref([])
	const list2 = ref([])
	const provinces = ref([])
	const citys = ref([])
	const areas = ref([])
	const addressIds = ref(user.addressIds)
	const addressName = ref(user.addressName)
	const addressPicker = ref(null)
	const addressList = computed(() => [provinces.value, citys.value, areas.value])
	const showActivity = ref(false)
	const scene = ref(0)
	const goodsList = ref([])
	
	function init() {
		refreshList()
		initArea()
		getBanner()
		initActivity('2025/05/04 00:00:00')
		initGoods()
	}
	function swiperChange(e) {
		curSwiper.value = e.detail.current
	}
	function openPage(url) {
		if(url) uni.navigateTo({url})
		else uni.showToast({icon: 'none',title: '敬请期待！'})
	}
	function changeList(e) {
		if(e.name === 'list1') list1.value.push(e.value)
		else if(e.name === 'list2') list2.value.push(e.value)
	}
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		videoList.value = []
		list1.value = []
		list2.value = []
		query.value.current = 1
		getVideoList(query.value).then(res => {
			let result = res.result || {}
			// let data = dealVideoData(result.records || [])
			let data = result.records || []
			total.value = Number(result.total)
			videoList.value = data
			let curLength = videoList.value.length
		}).catch(() => loadStatus.value = 'nomore')
	}
	function lowerList() {
		if(videoList.value.length < total.value) {
			loadStatus.value = 'loading'
			query.value.current ++
			getVideoList(query.value).then(res => {
				let result = res.result || {}
				// let data = dealVideoData(result.records || [])
				let data = result.records || []
				total.value = Number(result.total)
				videoList.value.push(...data)
				let curLength = videoList.value.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function dealVideoData(arr) {
		const v = uni.upx2px(750) - 12 - 12 - 13
		let list = arr.map(item => {
			let h = 344
			if(item.cover) {
				if(item.cover.meta) {
					let meta = JSON.parse(item.cover.meta)
					const w = v/2
					const rate = w / meta.width
					h = Math.floor(rate * meta.height)
				}
			}
			item.height = h
			let d = 0
			if(item.annex) {
				if(item.annex.meta) {
					let meta = JSON.parse(item.annex.meta)
					d = timestampToTime(Math.ceil(meta.time || 0))
				}
			}
			item.duration = d
			return item
		})
		return list
	}
	function openVideo(id) {
		let url = '/pages/videoPlay?id=' + id
		uni.navigateTo({url})
	}
	function initArea() {
		if(!provinces.value.length) {
			loading.value = true
			getAddressList().then(res => {
				let result = res.result || []
				provinces.value = result
				setTimeout(() => {
					handleAddressDefault()
					loading.value = false
				}, 500)
			}).catch(() => loading.value = false)
		}
	}
	function handleAddressDefault() {
		let addressValue = [0, 0, 0]
		addressValue[0] = provinces.value.findIndex(item => item.areaId === addressIds.value[0])
		citys.value = provinces.value[addressValue[0]]?.children || []
		addressValue[1] = citys.value.findIndex(item => item.areaId === addressIds.value[1])
		areas.value = citys.value[addressValue[1]]?.children || []
		addressValue[2] = areas.value.findIndex(item => item.areaId === addressIds.value[2])
		addressPicker.value.setIndexs(addressValue, true)
	}
	function selectArea() {
		if(areas.value.length) {
			addressPicker.value.open()
			setTimeout(() => {
				handleAddressDefault()
			}, 500)
		} else {
			uni.showToast({icon: 'none', title: '暂无地区数据'})
		}
	}
	function changeAddress(e) {
		if (loading.value) return
		const { columnIndex, index, indexs } = e
		if (columnIndex === 0) {
			citys.value = provinces.value[index]?.children || []
			areas.value = citys.value[0]?.children || []
			addressPicker.value.setIndexs([index, 0, 0], true)
		} else if (columnIndex === 1) {
			areas.value = citys.value[index]?.children || []
			addressPicker.value.setIndexs(indexs, true)
		}
	}
	function confirmAddress(e) {
		let value = e.value
		let name = value[1].areaName + value[2].areaName
		let ids = [value[0].areaId, value[1].areaId, value[2].areaId]
		addressName.value = name
		addressIds.value = ids
		user.addressAction(name, ids)
		getBanner()
		initGoods()
	}
	function openSetting() {
		uni.openSetting()
	}
	function getBanner() {
		getBannerList({areaId: addressIds.value[2]}).then(res => {
			let arr = res.result || []
			navImg.value = arr
		})
	}
	function initActivity(timeStr) {
		let nowTimeStamp = +new Date()
		let endTimeStamp = +new Date(timeStr)
		showActivity.value = nowTimeStamp < endTimeStamp
	}
	function initGoods() {
		if(!scene.value) return
		goodsList.value = []
		getSpecialOffer({areaId: addressIds.value[2]}).then(res => {
			let arr = res.result || []
			goodsList.value = arr
		})
	}
	function goBuy(item) {
		if(loading.value) return
		loading.value = true
		let data = {
			total: item.price,
			list: [{
				id: item.goodsId,
				name: item.goodsName,
				furl: item.images && item.images[0] && item.images[0].furl || '',
				price: item.price,
				number: 1,
				type: 'INGREDIENT'
			}]
		}
		uni.navigateTo({
			url: '/pages/shop/orderConfirm',
			success: res => {
				res.eventChannel.emit('orderConfirm', data)
			}
		})
		loading.value = false
	}
	function goView(item) {
		let url = `/pages/shop/goodsDetail?id=${item.goodsId}&title=${item.goodsName}`
		uni.navigateTo({url})
	}
	function consult() {
		uni.makePhoneCall({
			phoneNumber: '400-113-0871'
		})
	}
	
	onLoad((option) => {
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		statusHeight.value = menuButtonInfo.top
		menuHeight.value = menuButtonInfo.height
		menuWidth.value = menuButtonInfo.right
		contHeight.value = menuButtonInfo.bottom + 10
		// #endif
		if(user.userId) user.shopCarAction(false, true)
		if(option.scene) scene.value = option.scene
		init()
	})
	onReachBottom(() => {
		lowerList()
	})
	onPageScroll((e) => {
		headOpacity.value = e.scrollTop > 120 ? 1 : e.scrollTop / 120
		if(e.scrollTop > 400) {
			uni.setTabBarItem({
				index: 0,
				text: '回顶部',
				selectedIconPath: 'static/images/tabbar/back.png'
			})
		} else {
			uni.setTabBarItem({
				index: 0,
				text: '首页',
				selectedIconPath: 'static/images/tabbar/home_.png'
			})
		}
	})
	onPullDownRefresh(() => {
		if(waterfall.value) {
			waterfall.value.clear()
		}
		init()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 300)
	})
	onTabItemTap((e) => {
		if(e.index === 0 && e.text === '回顶部') {
			uni.startPullDownRefresh()
		}
	})
	onShareAppMessage(() => {
		return {
			title: config.appInfo.name,
			path: '/pages/tabbar/index',
			imageUrl: config.appInfo.logo
		}
	})
	onShow(() => {
		
	})
	onHide(() => {
		
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head" :style="{backgroundColor: 'rgba(254, 109, 93, ' + headOpacity.toFixed(1) + ')', height: contHeight + 'px'}">
			<view class="status-menuButton" :style="{ height: statusHeight + 'px' }"></view>
			<view class="area-box" :style="{height: menuHeight + 'px',maxWidth: menuWidth? menuWidth + 'px' : '100%'}" @click="selectArea">
				<uv-icon name="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-11/1739260928418_map.png" size="36" />
				<text>{{citys.length? addressName : '地区选择'}}</text>
				<uv-icon name="arrow-right" color="#FFFFFF" size="26" />
			</view>
		</view>
		<view class="app-content">
			<view class="content-box">
				<swiper class="content-swipe" circular autoplay @change="swiperChange">
					<swiper-item v-for="item in navImg" :key="item.bannerId">
						<image :src="item.images && item.images[0] && item.images[0].furl" class="image" mode="aspectFill"></image>
					</swiper-item>
				</swiper>
				<view class="dot-box">
					<view :class="['dot-item', curSwiper == index? 'active' : '' ]" v-for="(item, index) in navImg" :key="item.bannerId"></view>
				</view>
			</view>
			<view class="content-nav">
				<view class="nav-item" @click="openPage('/pages/shop/deviceAgree?type=1')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-24/1750747985517_nav-0.png" class="icon" mode="aspectFill" />
					<text>智慧餐车</text>
				</view>
				<!-- <view class="nav-item" @click="openPage('/pages/shop/deviceAgree?type=2')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-04-03/1743644843342_nav-7.png" class="icon" mode="aspectFill" />
					<text>办宴设备设施</text>
				</view> -->
				<!-- <view class="nav-item" @click="openPage('/pages/shop/specialDish')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-12/1739331592713_nav-1.png" class="icon" mode="aspectFill" />
					<text>办宴套餐</text>
				</view> -->
				<view class="nav-item" @click="openPage('/pages/shop/kitchenRecom')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-24/1750747988157_nav-4.png" class="icon" mode="aspectFill" />
					<text>厨师推荐</text>
				</view>
				<view class="nav-item" @click="openPage('/pages/shop/foodSelect')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-24/1750747993967_nav-6.png" class="icon" mode="aspectFill" />
					<text>食材直供</text>
				</view>
				<!-- <view class="nav-item" @click="openPage('/pages/shop/hostShow')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-12/1739331604860_nav-2.png" class="icon" mode="aspectFill" />
					<text>宴席文化</text>
				</view> -->
				<!-- <view class="nav-item" @click="openPage('/pages/shop/seckill')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-12/1739331618334_nav-3.png" class="icon" mode="aspectFill" />
					<text>特惠商品</text>
				</view> -->
				<view class="nav-item" @click="openPage('/pages/shop/banquetAdd')">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-24/1750747990699_nav-5.png" class="icon" mode="aspectFill" />
					<text>我要办宴</text>
				</view>
			</view>
			<view v-if="showActivity" class="activity-box" @click="openPage('/pages/activity/introduce')">
				<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-04-23/1745405750206_5.1-activity-icon.png"
					class="icon" mode="aspectFill" />
			</view>
			<view class="introduce-box">
				<uv-image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-07-02/1751445723179_des_0.png"
					width="342" height="342" radius="16" @click="openPage('/pages/activity/foodSafe')"></uv-image>
				<uv-image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-07-02/1751445725269_des_1.png"
					width="342" height="342" radius="16" @click="openPage('/pages/activity/goodQuality')"></uv-image>
				<uv-image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-07-02/1751445727455_des_2.png"
					width="342" height="342" radius="16" @click="openPage('/pages/activity/support')"></uv-image>
				<uv-image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-07-02/1751445730266_des_3.png"
					width="342" height="342" radius="16" @click="openPage('/pages/activity/bestService')"></uv-image>
			</view>
			<view class="goods-box" v-if="goodsList.length">
				<view class="goods-title">现场特卖</view>
				<view class="list-box">
					<view class="list-item" v-for="goods in goodsList" :key="goods.goodsId">
						<uv-image :src="goods.images && goods.images[0] && goods.images[0].furl" width="160" height="160" radius="16" 
							:custom-style="{border: '2rpx solid #FAF7F7'}"></uv-image>
						<view class="item-info">
							<view class="item-title uv-line-1">{{goods.goodsName || '--'}}</view>
							<view class="item-bottom theme-btn">
								<view class="item-price">
									<text class="text-price">{{goods.price || '--'}}</text>
									<text class="text-original" v-if="goods.linePrice">¥{{goods.linePrice}}</text>
								</view>
								<uv-button color="linear-gradient( 102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" size="small" text="马上抢" @click="goBuy(goods)" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<template v-if="videoList.length">
				<view class="nav-title">
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-11/1739267378016_nav-title.png"
						class="icon" mode="aspectFill" />
					<text>办宴视频</text>
					<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-11/1739267378016_nav-title.png" 
						class="icon rotate" mode="aspectFill" />
				</view>
				<uv-waterfall ref="waterfall" v-model="videoList" :add-time="200" :left-gap="24" :right-gap="24" :column-gap="26" @changeList="changeList">
					<template v-slot:list1>
						<!-- 为了磨平部分平台的BUG，必须套一层view -->
						<view>
							<view v-for="(item, index) in list1" :key="item.videoId" class="video-item">
								<channel-video class="channel-video" :finder-user-name="config.appInfo.finderUserName" :feed-id="item.feedId"></channel-video>
								<!-- <view class="video-image" :style="{height: item.height + 'px'}" @click="openVideo(item.videoId)">
									<uv-image :src="item.cover && item.cover.furl" width="100%" height="100%"></uv-image>
									<view class="video-time">{{item.duration || '00:00'}}</view>
								</view>
								<view class="video-bottom">
									<view class="video-title uv-line-2">{{item.title || ''}}</view>
									<view class="video-info">
										<view class="info-left">
											<uv-image :src="item.avatar && item.avatar.furl" width="34rpx" height="34rpx" shape="circle"></uv-image>
											<view class="info-left-text uv-line-1">{{item.createBy || ''}}</view>
										</view>
										<view class="info-right">
											<uv-icon :name="item.like? 'heart-fill' : 'heart'" color="#808080" size="20" />
											<view class="info-right-text uv-line-1">{{item.likeNum || 0}}</view>
										</view>
									</view>
								</view> -->
								<view class="video-bottom">
									<view class="video-title uv-line-2">{{item.title || ''}}</view>
								</view>
							</view>
						</view>
					</template>
					<template v-slot:list2>
						<!-- 为了磨平部分平台的BUG，必须套一层view -->
						<view>
							<view v-for="(item, index) in list2" :key="item.videoId" class="video-item">
								<channel-video class="channel-video" :finder-user-name="config.appInfo.finderUserName" :feed-id="item.feedId"></channel-video>
								<!-- <view class="video-image" :style="{height: item.height + 'px'}" @click="openVideo(item.videoId)">
									<uv-image :src="item.cover && item.cover.furl" width="100%" mode="widthFix"></uv-image>
									<view class="video-time">{{item.duration || '00:00'}}</view>
								</view>
								<view class="video-bottom">
									<view class="video-title uv-line-2">{{item.title || ''}}</view>
									<view class="video-info">
										<view class="info-left">
											<uv-image :src="item.avatar" width="34rpx" height="34rpx" shape="circle"></uv-image>
											<view class="info-left-text uv-line-1">{{item.createBy || ''}}</view>
										</view>
										<view class="info-right">
											<uv-icon :name="item.like ? 'heart-fill' : 'heart'" color="#808080" size="20" />
											<view class="info-right-text uv-line-1">{{item.likeNum || 0}}</view>
										</view>
									</view>
								</view> -->
								<view class="video-bottom">
									<view class="video-title uv-line-2">{{item.title || ''}}</view>
								</view>
							</view>
						</view>
					</template>
				</uv-waterfall>
				<view class="pad-bottom">
					<uv-load-more :status="loadStatus" fontSize="28" iconSize="34" isDot line marginTop="20" marginBottom="20"></uv-load-more>
				</view>
			</template>
		</view>
		
		<image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-06-30/1751265004988_consult.png" class="consult-box"
			mode="aspectFill" @click="consult" />
		<uv-picker ref="addressPicker" :columns="addressList" :loading="loading" keyName="areaName" @change="changeAddress" @confirm="confirmAddress" 
			visibleItemCount="10"></uv-picker>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		.app-head {
			position: fixed;
			top: 0;
			right: 0;
			left: 0;
			z-index: 10;
			padding-bottom: 10px;
			.area-box {
				padding: 0 16rpx 0 24rpx;
				display: flex;
				align-items: center;
				gap: 8rpx;
				color: #FFFFFF;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
			}
		}
		.app-content{
			padding-bottom: 24rpx;
		}
		.content-box{
			position: relative;
			.content-swipe{
				height: 724rpx;
				.image {
					width: 100%;
					height: 100%;
				}
			}
			.dot-box{
				position: absolute;
				z-index: 10;
				left: 0;
				bottom: 236rpx;
				width: 100%;
				height: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 10rpx;
				.dot-item{
					width: 10rpx;
					height: 10rpx;
					background-color: rgba(255, 255, 255, 0.5);
					border-radius: 10rpx;
					&.active{
						width: 40rpx;
						background-color:  #FFFFFF;
					}
				}
			}
		}
		.content-nav{
			position: relative;
			z-index: 9;
			margin: -220rpx 24rpx 16rpx;
			padding: 24rpx 0;
			display: flex;
			gap: 24rpx 1rpx;
			background-color: #FFFFFF;
			border-radius: 24rpx;
			.nav-item{
				width: 174rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				gap: 16rpx;
				.icon {
					width: 108rpx;
					height: 108rpx;
					border-radius: 32rpx;
				}
			}
		}
		.nav-title{
			padding: 24rpx 32rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 16rpx;
			font-weight: 800;
			color: #F92E1D;
			font-size: var(--theme-lg);
			line-height: var(--theme-lg-line);
			.icon{
				width: 18rpx;
				height: 16rpx;
				&.rotate{
					transform: rotate(180deg);
				}
			}
		}
		.video-item {
			margin-bottom: 32rpx;
			width: 338rpx;
			overflow: hidden;
			border-radius: 16rpx;
			background-color: #FFFFFF;
			.channel-video{
				width: 100%;
				height: 186rpx;
			}
			.video-image{
				position: relative;
				.video-time{
					position: absolute;
					bottom: 16rpx;
					right: 16rpx;
					z-index: 2;
					color: #A9A9A9;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
			}
			.video-bottom{
				padding: 12rpx;
				font-size: var(--theme-sm);
				line-height: var(--theme-sm-line);
				box-shadow: 8rpx 8rpx 16rpx 0rpx rgba(0,0,0,0.04);
				.video-title{
					color: #000000;
					margin-bottom: 8rpx;
				}
				.video-info{
					display: flex;
					justify-content: space-between;
					align-items: center;
					color: #C4C4C4;
					.info-left{
						width: 68%;
						display: flex;
						align-items: center;
						gap: 8rpx;
						.info-left-text{
							width: calc(100% - 36rpx);
						}
					}
					.info-right{
						width: 30%;
						display: flex;
						justify-content: flex-end;
						align-items: center;
						gap: 4rpx;
						.info-right-text{
							max-width: calc(100% - 28rpx);
						}
					}
				}
			}
		}
		.pad-bottom{
			padding-bottom: 2rpx;
		}
		.activity-box{
			padding: 16rpx 24rpx 0;
			.icon{
				width: 100%;
				height: 144rpx;
				border-radius: 24rpx;
			}
		}
		.introduce-box{
			padding: 16rpx 24rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-wrap: wrap;
			gap: 18rpx 16rpx;
		}
		.goods-box{
			margin: 16rpx 24rpx 0;
			padding-bottom: 24rpx;
			border-radius: 24rpx;
			background-color: #FFFFFF;
			.goods-title{
				padding: 24rpx 24rpx 20rpx;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
				font-weight: 900;
			}
			.list-box{
				padding: 0 24rpx;
				display: flex;
				flex-direction: column;
				gap: 40rpx;
				.list-item{
					display: flex;
					gap: 16rpx;
					.item-info{
						width: calc(100% - 176rpx);
						padding: 8rpx 0;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
					}
					.item-title{
						font-weight: 600;
					}
					.item-bottom{
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
					.item-price{
						.text-price{
							font-size: var(--theme-lg);
							color: #FF1313;
							font-weight: 600;
							&::before{
								content: "¥";
								font-size: 60%;
							}
						}
						.text-original{
							margin-left: 8rpx;
							font-size: var(--theme-sm);
							color: #999999;
							text-decoration-line: line-through;
						}
					}
				}
				.list-item + .list-item{
					margin-left: 8rpx;
				}
			}
		}
		.consult-box{
			position: fixed;
			bottom: 118rpx;
			right: 0;
			z-index: 10;
			width: 180rpx;
			height: 176rpx;
		}
	}
</style>